package com.clouddot.baipai.ui.fragment.H;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIClassFragmentComponent;
import com.clouddot.baipai.contract.IClassFragmentContract;
import com.clouddot.baipai.http.entity.response.getClassHonorResponse;
import com.clouddot.baipai.http.entity.response.getClassInfoByIdResponse;
import com.clouddot.baipai.http.entity.response.getClassInfoListResponse;
import com.clouddot.baipai.http.entity.response.getClassMemberResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.ClassFragmentModule;
import com.clouddot.baipai.ui.Dialog.H_ContentDailog;
import com.clouddot.baipai.ui.activity.H_UMainActivity;
import com.clouddot.baipai.ui.adapter.H_ClassHonorAdapter;
import com.clouddot.baipai.ui.adapter.H_ClassInfoAdapter;
import com.clouddot.baipai.ui.adapter.H_ClassMemberAdapter;
import com.clouddot.baipai.util.EscapeUnescapeUtil;
import com.clouddot.baipai.util.SelectedBtnUtil;
import com.clouddot.baipai.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.ViewAnim;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_ONE;
import static com.clouddot.baipai.util.viewUtil.ViewUtil.imageGetter;


/**
 * Created by wxy on 2018/8/23.
 * 横版班牌班级的主页面
 */
public class H_ClassFrgment extends BaseFragment implements IClassFragmentContract.IView {
    //存放请求回来的班级通知列表或者班级活动列表
    private List<getClassInfoListResponse.classInfoItem>  classInfoItemList= new ArrayList<>();
    //存放请求回来的班级荣誉列表
    private List<getClassHonorResponse.honorInfo> honorInfoList = new ArrayList<>();
    //存放请求回来的班级成员列表
    private List<getClassMemberResponse.studentInfo> studentInfoList = new ArrayList<>();
    //班级通知的适配器
    private H_ClassInfoAdapter getHClassInfoAdapter;
    //班级荣誉的适配器
    private H_ClassHonorAdapter getHClassHonorAdapter;
    //班级成员的适配器
    private H_ClassMemberAdapter getHClassMemberAdapter;
    //用来记录当前的item
    private String currentItem = "notice";
    //用来记录当前的点击的item是否一致
    private String currentDataType = "";
    //用来记录当前的page
    private int currentPage = 1;
    private TextView[] textViews = new TextView[4];
    private H_ContentDailog dailog;
    private boolean isRunning = false;

    @Inject
    IClassFragmentContract.IPresenter mPresenter;
    @BindView(R.id.RecyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.class_notice)
    TextView class_notice;
    @BindView(R.id.class_activity)
    TextView class_activity;
    @BindView(R.id.class_honor)
    TextView class_honor;
    @BindView(R.id.class_member)
    TextView class_member;
    @BindView(R.id.leftLoading)
    ImageView leftLoading;
    @BindView(R.id.loadingLP)
    RelativeLayout loadingLP;
    @BindView(R.id.no)
    ImageView no;

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.h_fragment_class, null);

    }
    @Override
    protected void initViews() {
        DaggerIClassFragmentComponent.builder().classFragmentModule(new ClassFragmentModule(this)).build().inject(this);
        mPresenter.getClassInfoList(1,currentItem, Env.getAppContext().ClassID,currentPage,8);
    }

    @Override
    protected void initVariables() {
        Animation loadingAnim = ViewAnim.getRotateImg(getActivity());
        leftLoading.startAnimation(loadingAnim);
        textViews[0]=class_notice;textViews[1]=class_activity;textViews[2]=class_honor;textViews[3]=class_member;
        SelectedBtnUtil.selectedforText(textViews,textViews[0]);
        recyclerView.addOnScrollListener(H_UMainActivity.listener);
    }

    @OnClick({R.id.class_notice,R.id.class_activity,R.id.class_honor,R.id.class_member})
    public void onClick(View view){
        H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
        if(!isRunning) {
            isRunning = true;
            loadingLP.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            no.setVisibility(View.GONE);
            currentDataType = "";
            currentPage = 1;
            switch (view.getId()) {
                case R.id.class_notice:
                    currentItem = "notice";
                    classInfoItemList.clear();
                    mPresenter.getClassInfoList(1, currentItem, Env.getAppContext().ClassID, currentPage, 8);
                    SelectedBtnUtil.selectedforText(textViews, textViews[0]);
                    break;
                case R.id.class_activity:
                    currentItem = "activity";
                    classInfoItemList.clear();
                    mPresenter.getClassInfoList(1, currentItem, Env.getAppContext().ClassID, currentPage, 8);
                    SelectedBtnUtil.selectedforText(textViews, textViews[1]);

                    break;
                case R.id.class_honor:
                    currentItem = "honor";
                    honorInfoList.clear();
                    mPresenter.getClassHonorList(Env.getAppContext().ClassID, currentPage, 5);
                    SelectedBtnUtil.selectedforText(textViews, textViews[2]);
                    break;
                case R.id.class_member:
                    currentItem = "member";
                    studentInfoList.clear();
                    mPresenter.getClassMemberList(Env.getAppContext().ClassID, currentPage, 30);
                    SelectedBtnUtil.selectedforText(textViews, textViews[3]);
                    break;
            }
        }
    }

    @Override
    protected void loadData() {}


    /**
     * fragment 隐藏和显现触发的方法，第一次生成的时候不会触发。
     *  hidden 为 false --> 显现 ；为 true --> 隐藏
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            class_notice.performClick();
        }
    }


    /**
     *
     * @param flag 1 --> 获取班级通知或者班级活动
     *             2 --> 获取班级荣誉
     *             3 --> 获取班级成员
     *             4 --> 点击班级活动或者通知时候 ，获取item内容
     * @param object
     */
    @Override
    public void success(int flag ,Object object) {
        if (flag ==1) {
            refulesClassNoticeAndActivity(object);
        }else if(flag == 2){
            refulesClassHonor(object);
        }else if(flag == 3){
            refulesClassMember(object);
        }else if(flag == 4){
            refulesClassListInfo(object);
        }
        loadingLP.setVisibility(View.GONE);
        isRunning = false;
    }

    @Override
    public void fail(int flag ,String errMsg) {
        ToastUtil.showToast(getActivity(),errMsg);
        loadingLP.setVisibility(View.GONE);
        isRunning = false;


    }

    /**
     * 更新班级通知和活动数据
     * @param object
     */
    private void refulesClassNoticeAndActivity(Object object){
        getClassInfoListResponse response = (getClassInfoListResponse) object;
        if(response.EntityList.isEmpty()) {
            if(classInfoItemList.isEmpty()) no.setVisibility(View.VISIBLE);
            if(getHClassInfoAdapter != null) getHClassInfoAdapter.loadMoreEnd();
            return;
        }
        if(!currentDataType.equals(currentItem)) {
            classInfoItemList = response.EntityList;
            LinearLayoutManager mLayoutManager=new LinearLayoutManager(getActivity());
            mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            getHClassInfoAdapter = new H_ClassInfoAdapter(classInfoItemList);
            getHClassInfoAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    mPresenter.getClassInfoList(1,currentItem,Env.getAppContext().ClassID,++currentPage,8);
                }
            });
            getHClassInfoAdapter.setOnClickListener(new H_ClassInfoAdapter.AdapterItemClickListener() {
                @Override
                public void onClicked(String position) {
                    H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                    mPresenter.getClassInfoById(position);
                }
            });
            recyclerView.setAdapter(getHClassInfoAdapter);
            currentDataType = currentItem;
            recyclerView.setVisibility(View.VISIBLE);
        }else{
            getHClassInfoAdapter.addData(response.EntityList);
            getHClassInfoAdapter.loadMoreComplete();
        }
    }

    /**
     * 更新班级荣誉数据
     * @param object
     */
    private void refulesClassHonor(Object object){
        getClassHonorResponse response = (getClassHonorResponse) object;
        if(response.EntityList.isEmpty()) {
            if(honorInfoList.isEmpty()) no.setVisibility(View.VISIBLE);
            if(getHClassHonorAdapter != null) getHClassHonorAdapter.loadMoreEnd();
            return;
        }
        if(!currentDataType.equals(currentItem)){
            honorInfoList = response.EntityList;
            LinearLayoutManager mLayoutManager=new LinearLayoutManager(getActivity());
            mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            getHClassHonorAdapter = new H_ClassHonorAdapter(honorInfoList);
            getHClassHonorAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    mPresenter.getClassHonorList(Env.getAppContext().ClassID,++currentPage,5);
                }
            });
            recyclerView.setAdapter(getHClassHonorAdapter);
            currentDataType = currentItem;
            recyclerView.setVisibility(View.VISIBLE);

        }else{
            getHClassHonorAdapter.addData(response.EntityList);
            getHClassHonorAdapter.loadMoreComplete();
        }
    }

    /**
     * 更新班级人员数据
     * @param object
     */
    private void refulesClassMember(Object object){
        getClassMemberResponse response = (getClassMemberResponse) object;
        if(response.EntityList.isEmpty()){
            if(studentInfoList.isEmpty()) no.setVisibility(View.VISIBLE);
            if(getHClassMemberAdapter != null) getHClassMemberAdapter.loadMoreEnd();
            return;
        }
        if(!currentDataType.equals(currentItem)){
            studentInfoList = response.EntityList;
            GridLayoutManager mLayoutManager=new GridLayoutManager(getActivity(),7, OrientationHelper.VERTICAL,false);
            mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            getHClassMemberAdapter = new H_ClassMemberAdapter(studentInfoList);
            getHClassMemberAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    mPresenter.getClassMemberList(Env.getAppContext().ClassID,++currentPage,30);
                }
            });
            recyclerView.setAdapter(getHClassMemberAdapter);
            currentDataType = currentItem;
            recyclerView.setVisibility(View.VISIBLE);

        }else{
            getHClassMemberAdapter.addData(response.EntityList);
            getHClassMemberAdapter.loadMoreComplete();
        }
    }

    /**
     * 点击item，弹出dialog显示班级通知内容或者活动内容
     * @param object
     */
    private void refulesClassListInfo(Object object){
        getClassInfoByIdResponse response = (getClassInfoByIdResponse) object;
         dailog = new H_ContentDailog(getActivity());
        dailog.showDialog();
        dailog.getCloseView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                dailog.closeDialog();
            }
        });
        if(!response.Id.isEmpty()) {
            dailog.getTextViews().get(0).setText(response.Title);
            dailog.getTextViews().get(1).setText(response.CreateTime);
            if(response.Detail !=null && !response.Detail.isEmpty()) {
                final String html = EscapeUnescapeUtil.unescape(response.Detail);
                ThreadPoolFactory.getThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        final Spanned sp = Html.fromHtml(html, imageGetter, null);
                        Message message = new Message();
                        message.what = MSG_ONE;
                        message.obj = sp;
                        handler.sendMessage(message);
                    }
                });
            }
        }else{
            dailog.getTextViews().get(0).setText("内容为空，请检查数据完整性！");
        }

    }


    /**
     * handle机制更新页面
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    if (dailog!=null) dailog.getTextViews().get(2).setText((Spanned)msg.obj);
                    break;
            }
        }
    };



}
